package jch.learn.java.advanced.chapter2_InputAndOutput.objectStream;

import java.io.*;

public class ObjectStreamSingleTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        String path = ObjectStreamSingleTest.class.getResource("/chapter2/testSingle.dat").getPath();

        Orientation original = Orientation.HORIZONTAL;

        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path));
        out.writeObject(original);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(path));
        Orientation newOriginal = (Orientation) in.readObject();

        if (newOriginal == original){
            System.out.println("单例对象序列化-反序列后是同一个对象！");
        }else{
            System.out.println("单例对象序列化-反序列化后不是同一个对象！");
        }


        System.out.println("单例和类型安全的枚举类增加readResolve()处理方法：");
        OrientationSingle single = OrientationSingle.VALUE_1;

        String singlePath = ObjectStreamSingleTest.class.getResource("/chapter2/single.dat").getPath();

        // 输出单例对象信息到文件
        ObjectOutputStream singleOut = new ObjectOutputStream(new FileOutputStream(singlePath));
        singleOut.writeObject(single);
        singleOut.close();

        // 从文件读入单例对象信息
        ObjectInputStream singleIn = new ObjectInputStream(new FileInputStream(singlePath));
        OrientationSingle newSingle = (OrientationSingle) singleIn.readObject();
        if (newSingle == single){
            System.out.println("单例对象序列化-反序列后是同一个对象！");
        }else{
            System.out.println("单例对象序列化-反序列化后不是同一个对象！");
        }

    }

}
